import axios from 'axios'
import Vue from 'vue'
import router from '@/router/router'
import store from '@/store'
// import { message, Modal } from "ant-design-vue";

const restr = localStorage.getItem('re')
export const Instance = axios.create({
  baseURL: process.env.VUE_APP_TAGURL,
  timeout: 300000
})

// 是否正在刷新的标志
let isTokenRefreshing = false
// 存储请求的数组
let subscribesArr = []

// 请求push到数组中
function subscribesArrRefresh(cb) {
  subscribesArr.push(cb)
}

// 用新token发起请求
function reloadSubscribesArr(newToken) {
  subscribesArr.map(cb => cb(newToken))
}

function isTokenExpire(serverTokenExpire) {
  const timestmp = new Date().getTime()
  return timestmp >= serverTokenExpire
}

Instance.interceptors.request.use(
  function(config) {
    // 判断token是否过期
    // get参数编码
    if (config.method === 'get' && config.params) {
      config.url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        config.url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
      config.url = config.url.substring(0, config.url.length - 1)
      config.params = {}
    }
    // config.headers.productLine = 'criteo'
    config.headers.productLine = process.env.VUE_APP_TAGNAME
    const serverTokenExpire = window.localStorage.getItem('exptime')
    if (serverTokenExpire && isTokenExpire(serverTokenExpire)) {
      // 判断token是否已经刷新过
      if (!isTokenRefreshing) {
        isTokenRefreshing = true
        // 请求刷新token
        axios.get(process.env.VUE_APP_BASEURL + 'Login/refreshToken', {
          params: {
            refreshToken: restr.slice(2)
          },
          headers: {
            authorization: ''
          }
        }).then(res => {
          // loading.close()
          if (res.data.data.isError) {
            subscribesArr = []
            localStorage.removeItem('exptime')
            localStorage.removeItem('ac')
            localStorage.removeItem('re')
            router.push('/Login')
          } else {
            store.commit('userInfo/$_refreshToken', {
              accessToken: res.data.data.accessToken,
              refreshToken: res.data.data.refreshToken,
              expiresIn: res.data.data.expiresIn
            })
            reloadSubscribesArr(res.data.data.accessToken)
          }
        })
          .catch(err => {
            console.log(err)
            isTokenRefreshing = false
            subscribesArr = []
            router.push('/Login')
          }).finally(() => {
            isTokenRefreshing = false
          })
      }
      const retry = new Promise(resolve => {
        subscribesArrRefresh(newToken => {
          Instance.defaults.headers.common['Authorization'] = 'Bearer ' + newToken
          config.headers.Authorization = 'Bearer ' + newToken
          resolve(config)
        })
      })
      return retry
    } else {
      config.headers.Authorization = 'Bearer ' + (window.localStorage.getItem('ac') || '').slice(2)
      return config
    }
  },
  err => {
    return Promise.reject(err)
  }
)

Instance.interceptors.response.use(
  function(res) {
    const link = res.config.url.split('api')[2] || []
    if (link.includes('isExport') && res.headers['content-type'].includes('json')) {
      return Promise.resolve(res.data.data)
    }
    if ((res.data == null || res.data.data == null) && link === '/Report/customTablePlan') {
      return Promise.resolve('[]')
    }
    // if (res.config.url.lastIndexOf('usage/api/status') === -1) {
    //   return Promise.resolve('[]')
    // }
    if (res.data.code && res.data.code !== 200) {
      // Vue.prototype.$pacLoading('hide')
      // Vue.prototype.$message.error(res.data.msg)
      return Promise.reject(res)
    } else {
      if (res.config.method === 'delete') {
        Vue.prototype.$message.success('Delete Successfully.')
        return Promise.resolve(res.data.code)
      } else {
        // 是否是下载
        if (res.headers['content-disposition']) {
          const disposition = res.headers['content-disposition']
          const fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length)
          return Promise.resolve({
            fileName,
            blob: res.data
          })
        } else {
          return Promise.resolve(res.data.data)
        }
      }
    }
  },
  err => {
    Vue.prototype.$pacLoading('hide')
    // loading.close()
    let status = 0
    if (err && err.response) {
      status = err.response.status
      err.msg = err.response.data.message
    }
    // 捕捉token过期时,跳转到登录页
    if (status === 401) {
      router.push('/Login')
      return
    } else if (status === 403) {
      Vue.prototype.$message({
        type: 'error',
        message: 'You do not have permission to complete the operation.'
      })
    }
    // else {
    //   Vue.prototype.$message({
    //     type: "error",
    //     message: msg
    //   });
    // }
    return Promise.reject(err)
  }
)
export const tagRequest = Instance
